package com.imooc.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/15/18:10
 * @Description:
 * 配置打印用户请求的URL，IP,参数,方法，响应
 *
 * */
@Aspect
//@Component
public class WebLogAspect {

        private final Logger log = LoggerFactory.getLogger(WebLogAspect.class);

        @Pointcut("execution(public * com.imooc.*.controller..*.*(..))")
        public void webLog() { }

        @Before("webLog()")
        public void doBefore(JoinPoint joinPoint) {
            /**
             * 打印请求的一系列信息
             */
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            log.info("URL: " + request.getRequestURL().toString());
            log.info("HTTP_METHOD: " + request.getMethod());
            log.info("IP: " + request.getRemoteAddr());
            log.info("CLASS_METHOD: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.info("ARGS: " + Arrays.toString(joinPoint.getArgs()));
        }

        @AfterReturning(pointcut = "webLog()",returning = "res")
        public void doAfterReturning(Object res) throws JsonProcessingException {
            //处理完请求返回内容
//            log.info("RESPONSE: "+new ObjectMapper().writeValueAsString(res));
        }
    }


